import json
import os
from pathlib import Path


class Config:
    """配置管理类"""
    
    def __init__(self):
        self.config_file = "config.json"
        self.default_config = {
            "cs2_path": "",
            "server_address": "sh_aliyun2.vincentzyu233.cn:20723",
            "server_password": "VincentZyu",
            "window_geometry": {
                "x": 100,
                "y": 100,
                "width": 800,
                "height": 600
            }
        }
        self.config = self.load_config()
    
    def load_config(self):
        """加载配置文件"""
        if os.path.exists(self.config_file):
            try:
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    config = json.load(f)
                    # 合并默认配置，确保所有键都存在
                    for key, value in self.default_config.items():
                        if key not in config:
                            config[key] = value
                    return config
            except (json.JSONDecodeError, FileNotFoundError):
                pass
        return self.default_config.copy()
    
    def save_config(self):
        """保存配置文件"""
        try:
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(self.config, f, indent=4, ensure_ascii=False)
        except Exception as e:
            print(f"保存配置失败: {e}")
    
    def get(self, key, default=None):
        """获取配置值"""
        return self.config.get(key, default)
    
    def set(self, key, value):
        """设置配置值"""
        self.config[key] = value
        self.save_config()
    
    def get_nested(self, *keys):
        """获取嵌套配置值"""
        value = self.config
        for key in keys:
            if isinstance(value, dict) and key in value:
                value = value[key]
            else:
                return None
        return value
    
    def set_nested(self, *args):
        """设置嵌套配置值，最后一个参数是值"""
        keys = args[:-1]
        value = args[-1]
        
        config = self.config
        for key in keys[:-1]:
            if key not in config:
                config[key] = {}
            config = config[key]
        
        config[keys[-1]] = value
        self.save_config()